use clap::Parser;
use std::io::{self, Read, Write};
use std::net::TcpStream;

/// Simple program to greet a person
#[derive(Parser, Debug)]
#[clap(author, version, about, long_about = None)]
struct Args {
    /// Name of the person to greet
    #[clap(short, long, default_value = "127.0.0.1")]
    host: String,

    /// Number of times to greet
    #[clap(short, long, default_value_t = 10001)]
    port: u32,

    /// Number of times to greet
    #[clap(short = 's', long, default_value = "123456")]
    password: String,
}

fn main() {
    let args = Args::parse();

    let mut addrs_info = String::new();

    addrs_info.push_str(args.host.as_str());
    addrs_info.push_str(args.port.to_string().as_str());

    let mut stream = TcpStream::connect(addrs_info).expect("connect failed");

    let mut buf = String::new();
    loop {
        buf.clear();
        match stream.read_to_string(&mut buf) {
            Ok(_usize) => {
                // println!("sys:{}", buf);
                io::stdout()
                    .write_fmt(format_args!("sys:{}", buf))
                    .unwrap_or_else(|e| println!("err:{}", e.to_string()));
            }
            Err(e) => {
                println!("err:{}", e.to_string());
            }
        };

        buf.clear();
        let result = io::stdin().read_line(&mut buf);
        let size = match result {
            Ok(size) => size,
            Err(e) => {
                println!("err:{}", e.to_string());
                continue;
            }
        };
        buf.push_str("\n");

        match stream.write(&buf.as_bytes()[..size]) {
            Err(e) => println!("error:{}", e.to_string()),
            _ => {
                continue;
            }
        }

        match stream.flush() {
            Err(e) => println!("error:{}", e.to_string()),
            _ => {
                continue;
            }
        }
    }
}
